package com.example.petplatform.Utils;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.petplatform.entity.Users;
import com.example.petplatform.exception.CustomException;
import com.example.petplatform.service.LoginService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * JWT拦截器
 */
public class JwtInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(JwtInterceptor.class);

    @Resource
    private LoginService loginService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //获取token
        String token = request.getHeader("token");
        if(StrUtil.isBlank(token)){
            token=request.getParameter(token);
        }
        //开始认证
        if(StrUtil.isBlank(token)){
            throw new CustomException("登录过期！,请重新登录");
        }
        //获取token中的adminId
        String adminId;
        Users users;
        try{
            adminId = JWT.decode(token).getAudience().get(0);
            //根据token中的userud查询数据库
            users=loginService.getAdminById(Integer.parseInt(adminId));
        }catch (Exception e){
            String errMsg="登录过期！，请重新登录";
            log.error(errMsg+",token="+token, e);
            throw new CustomException(errMsg);
        }
        if(users==null){
            throw new CustomException("用户不存在，请重新登录");
        }
        try{
//            用户加密签证认证 token
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(users.getPassword())).build();
            jwtVerifier.verify(token);
        }catch (JWTVerificationException e){
            throw new CustomException("登录过期！，请重新登录");
        }
        return true;
    }
}
